import axios from 'axios'
import router from '@/router'
import { ElMessage } from 'element-plus'

//创建实例
const request=axios.create({
  baseURL:'/api',
  timeout:600000
});
//添加请求拦截器 
request.interceptors.request.use((config)=>{
  //从lgcalStore获取数据
  let userInfo =localStorage.getItem('userInfo')
  if(userInfo){
    let token=JSON.parse(userInfo).token
    config.headers.token=token
  }
  return config;
},(error)=>{
  return Promise.reject(error);
});

//响应拦截
request.interceptors.response.use(
  (response)=>{//成功回调
    return response.data
  },
  (error)=>{//失败回调
    //401  路由跳转到/user/login
    if(error.response.status===401){
      ElMessage.error("身份失效,请重新登录!")
      router.push('/user/login')
    }else{
      return Promise.reject(error)
    }
  }
);
export default request;